import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;
import java.net.*;
import java.sql.*;

import javax.imageio.ImageIO;

import static java.lang.System.out;
public class PicClientThread extends Thread{
	 BufferedReader input;
		OutputStream output;
		 Socket myClientSocket;

	 public PicClientThread(Socket  client) {
		 myClientSocket = client;
	      // get input and output streams
	    	try{
	    	//	input = new BufferedReader( new InputStreamReader( client.getInputStream())) ;
	    		 output = myClientSocket.getOutputStream();


	     		// read name
	     	}catch( IOException e ){
	     	}
	     	start();
	 }
	 public void run(){
		receiveImage();
	 }
	 private void receiveImage(){
	    	BufferedImage buffer = null;
	    	System.out.println("Receive started");
	    	try{
		/*		int s;
				while((s=  input.read())>0){
					System.out.println(s);
				}
				*/
				/*
				System.out.println("1");
	    		InputStream img = myClientSocket.getInputStream();
				System.out.println("2");
				File myImage = new File("tmp.jpg");
				OutputStream out = new FileOutputStream(myImage);
				System.out.println("3");
				buffer = ImageIO.read(img);
				System.out.println("4");
				System.out.println(buffer.getHeight()+" "+buffer.getWidth());
				ImageIO.write(buffer,"jpg",myImage);
				System.out.println("5");
				*/

	    		InputStream img = myClientSocket.getInputStream();
	    		if(img!=null)System.out.println("Data received" );
	    		else System.out.println("Data receive fails");
	    		PreparedStatement myPrepareStatement = PichubServer.sqlCon.prepareStatement("INSERT INTO image(imageData) VALUES (?)",Statement.RETURN_GENERATED_KEYS);
	    		myPrepareStatement.setBinaryStream(1, img);
	    		myPrepareStatement.executeUpdate();
	    		ResultSet rs = myPrepareStatement.getGeneratedKeys();
	    		String returnStr = "";
	    		if(rs.next()){
	    			returnStr = rs.getInt(1)+"";
					System.out.println("IMAGE ID SENT BACK: "+returnStr+"");
	    		}

	    		output.write(returnStr.getBytes());
        		output.flush();
        		output.close();
			 	System.out.println("Image saved");
	    	}catch(Exception e){
	    		System.err.println("Receive");
	    		System.err.println(e);
	    	}
	    	System.out.println("Receive finished");
	    }
}
